<template>
    <div class="wh-100" style="background-color: white">
        <div  class="w-100  h-10 pl-24 fw-6 fs-18  d-flex-between-center">
            <div></div>
            <div class="d-flex pr-8">
                <el-select no-match-text="暂无数据"  no-data-text="暂无数据" v-model="pageParams.provinceName" clearable placeholder="请选择省份" @change="changeData">
                    <el-option v-for="item in aGivenYearSelect" :key="item.name" :label="item.name" :value="item.name"></el-option>
                </el-select>

                <el-button  size="small" class="ml-12" @click="dropExportAll">导出数据</el-button>
<!--                :before-upload="handleUpload"-->
                <el-button v-if="showLeadInto"  size="small" class="ml-12" @click="importFormView = true">导入数据</el-button>

                <Modal v-model="importFormView" title="导入毕业去向登记" v-loading="modelLoading">
                    <Form :model="importForm" :label-width="80" class="FormStyle">
                        <!--                                    <FormItem label="导入方式: ">-->
                        <!--                                        <RadioGroup v-model="importForm.importMode">-->
                        <!--                                            <Row>-->
                        <!--                                                <Radio label="1">增加记录(只增加新的记录,已存在的记录不变)</Radio>-->
                        <!--                                            </Row>-->
                        <!--                                            <Row>-->
                        <!--                                                <Radio label="2">覆盖记录(只对存在的记录进行更新)</Radio>-->
                        <!--                                            </Row>-->
                        <!--                                            <Row>-->
                        <!--                                                <Radio label="3">增加+覆盖记录</Radio>-->
                        <!--                                            </Row>-->
                        <!--                                        </RadioGroup>-->
                        <!--                                    </FormItem>-->
                        <FormItem label="文件: ">
                            <!--                                        <Upload accept=".xls, .xlsx,.dbf,.zip,.rar" :before-upload="handleUpload">-->
                            <!--                                            <Button icon="ios-cloud-upload-outline">点击上传</Button>-->
                            <!--                                        </Upload>-->
                            <Upload accept=".xlsx" :before-upload="handleUpload">
                                <Button icon="ios-cloud-upload-outline">点击上传</Button>
                            </Upload>
                            <div v-if="importForm.file !== null">
                                {{ importForm.file.name }}
                            </div>
                            <div>说明：请依据模板数据格式导入，文件格式必须为.xlsx</div>
                        </FormItem>
                    </Form>
                    <div slot="footer">
                        <Button @click="importFormcCncel">取消</Button>
                        <Button type="primary" :loading="importing" @click="importFormOk">开始上传</Button>
                    </div>
                </Modal>
            </div>
        </div>
        <div class="h-80 ">
                <el-table
                    v-loading="loading"
                    :height="heightNmber"
                    width="100%"
                    ref="formRef"
                    empty-text="暂无数据"
                    :header-cell-style="{ background: $backColor, color: '#333333' }"
                    :data="tableData"
                >
                    <el-table-column align="center" v-for="column in tableColumns" :key="column.prop" :prop="column.prop" :label="column.label" :width="column.width">
                        <el-table-column  align="center" v-if="column.children" v-for="item in column.children" :label="item.label" :width="item.width" :key="item.prop" :prop="item.prop">
                        </el-table-column>
                    </el-table-column>
                </el-table>

        </div>
        <div class="h-10 d-flex d-flex-center fs-14">
            <Page show-total :total="pageParams.total" :current="pageParams.pageNumber" :page-size="pageParams.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" show-sizer show-elevator />
        </div>
    </div>
</template>

<script>


import {
    exportAllArchiveTransferAddress,
    exportAllArchiveTransferInfo,
    getPageData
} from '../../api/archivesManagement/archiveForwardingAddressApis';
import { getProvinceAPI } from '../../api/bys';
import Cookies from 'js-cookie';
import cloneDeep from 'lodash/cloneDeep'
export default {
    data(){
        return{
            showLeadInto:false,
            checked: false,
            selectedRows: [], // 用于保存选择的行
            importForm: {
                file: null,
                importMode: '1'
            },
            aGivenYearSelect: [],
            loading: false,
            modelPosition: '',
            tableData: [],
            tableColumns: [],
            tableColumns_1: [
                {
                    prop: 'unitLocationProvinceName',
                    label: '城市（省份）名称',
                    width: '165'
                },
                {   prop: 'unitLocationCityName',
                    label: '所辖县（市、区）名称',
                    width: '165'
                },
                {
                    label: '师范生档案转递信息' ,
                    children: [
                        {
                            prop: 'normalUnitName',
                            label: '档案转递单位名称',
                            width: '450',
                        },
                        {
                            prop: 'normalUnitAddress',
                            label: '档案转递单位地址',
                            width: '450',
                        },
                        {
                            prop: 'normalUnitZip',
                            label: '档案转递单位邮编',
                            width: '135'
                        },
                        {
                            prop: 'normalUnitContact',
                            label: '档案转递联系人/联系部门',
                            width: '180'
                        },
                        {
                            prop: 'normalUnitTel',
                            label: '档案转递联系电话',
                            width: '135'
                        },
                        {
                            prop: 'normalUnitRemark',
                            width: '450',

                            label: '备注'
                        },
                    ]
                },
                {
                    label: '非师范生档案转递信息' ,
                    children: [
                        {
                            prop: 'notNormalUnitName',
                            label: '档案转递单位名称',
                            width: '450',
                        },
                        {
                            prop: 'notNormalUnitAddress',
                            label: '档案转递单位地址',
                            width: '450',
                        },
                        {
                            prop: 'notNormalUnitZip',
                            label: '档案转递单位邮编',
                            width: '135'
                        },
                        {
                            prop: 'notNormalUnitContact',
                            label: '档案转递联系人/联系部门',
                            width: '180'
                        },
                        {
                            prop: 'notNormalUnitTel',
                            label: '档案转递联系电话',
                            width: '135'
                        },
                        {
                            prop: 'notNormalUnitRemark',
                            width: '450',
                            label: '备注'
                        },
                    ]
                }
            ],
            pageParams: {
                pageSize: 10,
                pageNumber: 1,
                total: 0
            },
            heightNmber:'100%',
            openTip:true,
            selectList:[],
            importFormView: false,
            importing: false,
            modelLoading: false,
        }
    },
    mounted() {
        this.onRestWindow()
        window.addEventListener('resize',this.onRestWindow)

        this.showLeadInto = false

        let userInfo=JSON.parse(Cookies.get('userInfo'))
        if(userInfo.resource == 1){
            this.showLeadInto = true
        }
        this.getProvince();
        this.postData();
    },
    beforeDestroy() {
      window.removeEventListener('resize',this.onRestWindow)
    },
    methods: {
        onRestWindow() {
            let t1 = cloneDeep(this.tableColumns_1)
            this.restTreeTableCellWidth(t1)
            this.tableColumns = t1
        },
        changeData(){
            this.pageParams.pageNumber = 1;
            this.postData();
        },
        dropExportAll() {
            this.exportingAll = true;
            exportAllArchiveTransferAddress().then(res => {
                this.exportingAll = false;
                // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
                const blob = new Blob([res], { type: 'charset=utf-8' });
                let url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute('download', '档案转寄地址信息.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); // 删除节点
                window.URL.revokeObjectURL(url); //释放该 url
            });
        },
        changeTip(){
            this.openTip = !this.openTip
            if(this.openTip){
                this.heightNmber='95%'
            }else{
                this.heightNmber='100%'
            }
        },
        toggleSelection() {
            this.$refs.formRef.clearSelection();
        },
        postData: function() {
            getPageData(this.pageParams).then(res=>{
                console.log("res.................",res);
                this.tableData = res?.result?.records || [];
                this.pageParams.total = res.result.total || 0;

            })

        },
        //当选项改变时，保存选择的行
        handleSelectionChange(selectedRows) {
            this.selectedRows = selectedRows;
            this.selectList=selectedRows
            this.checked = selectedRows.length === this.tableData.length;
        },
        //下载模板
        downloadTemple() {
            // window.location.href = process.env.BASE_URL + 'xxxx年河南省生源信息查询统计表.xlsx';
        },
        importFormcCncel() {
            this.importForm.file = null;
            this.importFormView = false;
        },
        async importFormOk() {
            if (this.importForm.file == null) {
                this.$Message.info('请选择文件');
                return;
            }
            let formData = new FormData();

            formData.append('importMode', this.importForm.importMode); // 添加参数
            formData.append('file', this.importForm.file);
            this.importing = true;
            // fetch(baseUrl + '/bysJyqxInfo/import', {
            //     method: 'post',
            //     headers: {
            //         accessToken: accessToken
            //     },
            //     body: formData
            // })
            this.postRequest('/archiveTransferAddress/import', formData, { transformRequest: [] }).then(res => {
                if(res.code === 200){
                    this.$Message.success('导入成功');
                    this.tipMessage = '导入成功';
                    this.type = 'success';
                    this.importPromptVisible = true;
                    this.importing = false;
                    this.importFormcCncel();
                }
                // 下载
                // const url = window.URL.createObjectURL(res);
                // const link = document.createElement('a');
                // link.style.display = 'none';
                // link.href = url;
                // link.setAttribute('download', '导入失败数据汇总.xlsx');
                // document.body.appendChild(link);
                // link.click();
            });
            // .then(res => res.blob())
            //     this.postRequest( '/bysJyqxInfo/import', formData)


            // importDirectionAPI(formData).then(res => {
            //     if (res.code === 200) {
            //         this.tipMessage = res.message;
            //         this.type = 'success';
            //         this.importPromptVisible = true;
            //     } else if (res.code === 201) {
            //         this.tipMessage = res.message;
            //         this.type = 'warning';
            //         this.importPromptVisible = true;
            //         // this.$Message.success(res.message)
            //         const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
            //         const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            //         // 创建临时 URL 对象
            //         const url = URL.createObjectURL(blob);
            //         const downloadLink = document.createElement('a');
            //         downloadLink.href = url;
            //         downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
            //         downloadLink.click();
            //     } else {
            //         this.type = 'error';
            //         this.tipMessage = res.message;
            //         this.importPromptVisible = true;
            //         // this.$Message.error(res.message)
            //         const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
            //         const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            //         // 创建临时 URL 对象
            //         const url = URL.createObjectURL(blob);
            //         const downloadLink = document.createElement('a');
            //         downloadLink.href = url;
            //         downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
            //         downloadLink.click();
            //     }
            //     // this.submitLoading = false;
            //     this.importing = false;
            //     this.importFormcCncel();
            //     this.getDataList();
            // });
        },
        //导入
        handleUpload(file) {
            const fileExt = file.name
                .split('.')
                .pop()
                .toLocaleLowerCase();
            if (!(fileExt == 'xlsx' || fileExt == 'xls')) {
                this.$Notice.warning({
                    title: '文件类型错误',
                    desc: "所选文件'" + file.name + "'不是EXCEL文件，请选择后缀为.xlsx或者.xls的文件"
                });
            } else {
                this.importForm.file = file;
            }
            return false;
        },
        deleteInBatches() {
            const ids = this.selectedRows.map(row => row.id);
            delByIdsAPI({ ids: ids }).then(res => {
                console.log(res.message);
                this.$message.success(res.message);
                this.postData();
            });
        },
        //全选
        toggleAllSelection() {
            if (this.checked) {
                this.$refs.formRef.toggleAllSelection();
            } else {
                this.$refs.formRef.clearSelection();
            }
        },
        //获取年份
        getProvince() {
            getProvinceAPI().then(res => {
                this.aGivenYearSelect =res.result;
            });
        },
        //导入信息
        async exportMessage() {
            let formData = new FormData();
            formData.append('file', this.importForm.file);
            // addExcelAPI(formData).then(res => {
            //     if (res.code === 200) {
            //         this.$message.success(res.message);
            //         this.postData();
            //     } else if (res.code === 201) {
            //         this.$message.success(res.message);
            //         this.postData();
            //         const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
            //         const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            //         // 创建临时 URL 对象
            //         const url = URL.createObjectURL(blob);
            //         const downloadLink = document.createElement('a');
            //         downloadLink.href = url;
            //         downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
            //         downloadLink.click();
            //     } else {
            //         this.$Message.error(res.message);
            //         const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
            //         const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            //         // 创建临时 URL 对象
            //         const url = URL.createObjectURL(blob);
            //         const downloadLink = document.createElement('a');
            //         downloadLink.href = url;
            //         downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
            //         downloadLink.click();
            //     }
            // });
        },
        toDelete(id) {
            // delByIdAPI({ id: id }).then(res => {
            //     console.log(res.message);
            //     this.postData();
            // });
        },
        changePage: function(val) {
            this.pageParams.pageNumber = val;
            this.postData();
        },
        changePageSize: function(val) {
            this.pageParams.pageSize = val;
            this.postData();
        },
        // region TODO 查看详情跳转
        toDeails(id) {
            console.log(id);
            // this.$router.push({ name: 'DetailsOfStudentOrigin', query: { id: id } });
        },
        // endregion
        // region TODO 搜索
        toSearch() {
            this.postData();
        },
        // endregion

    }
};
</script>
<style scoped lang="less">
//form表单间距统一修改
.ivu-form-item {
    margin-bottom: 0.01rem !important;
}
</style>